var _wx$getSystemInfoSync = wx.getSystemInfoSync(),
  screenWidth = _wx$getSystemInfoSync.screenWidth,
  screenHeight = _wx$getSystemInfoSync.screenHeight
wx.setKeepScreenOn({ keepScreenOn: true })
function Canvas() {
  var canvas = wx.createCanvas();
  canvas.type = 'canvas';
  canvas.getBoundingClientRect = function () {
    var ret = {
      top: 0,
      left: 0,
      width: window.innerWidth,
      height: window.innerHeight
    };
    return ret;
  };
  canvas.style = {
    top: '0px',
    left: '0px',
    width: screenWidth + 'px',
    height: screenHeight + 'px'
  };

  canvas.addEventListener = function (type, listener) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    document.addEventListener(type, listener, options);
  };

  canvas.removeEventListener = function (type, listener) {
    document.removeEventListener(type, listener);
  };

  canvas.dispatchEvent = function () {
    var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    console.log('canvas.dispatchEvent', event.type, event);
  };

  Object.defineProperty(canvas, 'clientWidth', {
    enumerable: true,
    get: function get() {
      return screenWidth;
    }
  });

  Object.defineProperty(canvas, 'clientHeight', {
    enumerable: true,
    get: function get() {
      return screenHeight;
    }
  });
  return canvas;
}
var canvas = Canvas();
GameGlobal.screencanvas = canvas;
var gl = canvas.getContext("webgl");
var SCREEN_WIDTH, SCREEN_HEIGHT, ANCHOR_X;
if (canvas.height / 1500 > canvas.width / 852) {
  SCREEN_WIDTH = Math.ceil(canvas.height / 1500 * 852);
  SCREEN_HEIGHT = canvas.height;
  ANCHOR_X = (SCREEN_WIDTH - canvas.width) / SCREEN_WIDTH / 2
} else {
  SCREEN_WIDTH = canvas.width;
  SCREEN_HEIGHT = Math.ceil(canvas.width / 852 * 1500);
  ANCHOR_X = 0
}
var OFFSCREEN_WIDTH = SCREEN_WIDTH;
var OFFSCREEN_HEIGHT = SCREEN_HEIGHT;

function shaderSourceFromScript(scriptID) {
  if ("shader-vs" == scriptID) {
    return `
  attribute vec2 a_Position;
  attribute vec2 a_TexCoord;
  varying vec2 v_TexCoord;
  void main(void)
  {
      gl_Position = vec4(a_Position,0.0,1.0);
      v_TexCoord = a_TexCoord;
  }
`
  } else {
    return `   
    #ifdef GL_ES
    precision mediump float;
    #endif
    uniform sampler2D u_Sampler;
    varying vec2 v_TexCoord;
    void main() {
        gl_FragColor = texture2D(u_Sampler, v_TexCoord);
    }
`
  }
}
function compileShader(context, shaderVertexCode, shaderFragmentCode, vertexShaderobject, fragmentShaderObject) {
  context.shaderSource(vertexShaderobject, shaderVertexCode);
  context.shaderSource(fragmentShaderObject, shaderFragmentCode);
  context.compileShader(vertexShaderobject);
  context.compileShader(fragmentShaderObject);
  if (!context.getShaderParameter(vertexShaderobject, context.COMPILE_STATUS)) {
    return;
  }

  if (!context.getShaderParameter(fragmentShaderObject, context.COMPILE_STATUS)) {
    return;
  }
}
function linkShader(context, programObj, vertexShaderObj, fragmentShaderObj) {
  context.attachShader(programObj, vertexShaderObj);
  context.attachShader(programObj, fragmentShaderObj);
  context.linkProgram(programObj);
  if (!context.getProgramParameter(programObj, context.LINK_STATUS)) {
    return;
  }
  return programObj;
}

function initShader(context, cb) {
  var vertexShaderObj = context.createShader(context.VERTEX_SHADER);
  var fragmentShaderObj = context.createShader(context.FRAGMENT_SHADER);
  compileShader(context, shaderSourceFromScript("shader-vs"), shaderSourceFromScript("shader-fs"), vertexShaderObj, fragmentShaderObj);
  var programObj = context.createProgram();
  programObj = linkShader(context, programObj, vertexShaderObj, fragmentShaderObj);
  context.useProgram(programObj);
  cb(programObj);

}

function initArrayBuffer(gl, data, num, type) {
  var buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
  buffer.num = num;
  buffer.type = type;
  return buffer;
}

function initElementArrayBuffer(gl, data, type) {
  var buffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW);
  buffer.type = type;
  return buffer;
}

function initTextures(gl, cb) {
  var image = wx.createImage();
  image.onload = function () {
    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

    var u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');
    gl.uniform1i(u_Sampler, 0);

    gl.bindTexture(gl.TEXTURE_2D, null);

    cb(texture);
  };
  image.src = 'res/raw-assets/67/671f84aa-ae58-43df-957c-53ddfad87483.f6237.jpg';
}
function initPlane(gl) {
  var vertices = new Float32Array([
    1.0 - ANCHOR_X, -1.0,
    -1.0 - ANCHOR_X, -1.0,
    -1.0 - ANCHOR_X, 1.0,
    1.0 - ANCHOR_X, 1.0,
  ]);
  var texCoords = new Float32Array([
    1.0, 1.0,
    0.0, 1.0,
    0.0, 0.0,
    1.0, 0.0
  ]);

  var indices = new Uint8Array([
    0, 1, 2, 0, 2, 3
  ]);

  var plane = {};
  plane.vertexBuffer = initArrayBuffer(gl, vertices, 2, gl.FLOAT);
  plane.texCoordBuffer = initArrayBuffer(gl, texCoords, 2, gl.FLOAT);
  plane.indexBuffer = initElementArrayBuffer(gl, indices, gl.UNSIGNED_BYTE);
  plane.numIndices = indices.length;

  gl.bindBuffer(gl.ARRAY_BUFFER, null);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

  return plane;
}
function initAttributeVariable(gl, attributeName, buffer) {
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

  var attribute = gl.getAttribLocation(gl.program, attributeName);
  gl.vertexAttribPointer(attribute, buffer.num, buffer.type, false, 0, 0);
  gl.enableVertexAttribArray(attribute);
}
function initFramebufferObject(gl) {
  var framebuffer = gl.createFramebuffer();
  var texture = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  framebuffer.texture = texture;
  var depthBuffer = gl.createRenderbuffer();
  gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT);
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  var e = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  if (gl.FRAMEBUFFER_COMPLETE !== e) {
    console.log('Frame buffer object is incomplete: ' + e.toString());
    return;
  }
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.bindTexture(gl.TEXTURE_2D, null);
  gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  return framebuffer;
}

function drawPlane(gl, plane, texture) {
  initAttributeVariable(gl, 'a_Position', plane.vertexBuffer);
  initAttributeVariable(gl, 'a_TexCoord', plane.texCoordBuffer);
  var resolutionLocation = gl.getUniformLocation(gl.program, "u_resolution");
  gl.uniform2f(resolutionLocation, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT);
  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, plane.indexBuffer);
  gl.drawElements(gl.TRIANGLES, plane.numIndices, plane.indexBuffer.type, 0);
}

function draw(gl, plane, texture, fbo) {
  gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
  gl.viewport(0, 0, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT);
  gl.clearColor(0, 0, 0, 0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  drawPlane(gl, plane, texture); 
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.viewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  drawPlane(gl, plane, fbo.texture);
}
function onGetChid() {
  var query = wx.getLaunchOptionsSync().query;
  var referrerInfo = wx.getLaunchOptionsSync().referrerInfo; //新增 获取小程序通过extra-data参数 
  console.log('query', query)
  console.log('referrerInfo', referrerInfo)
  var chid = 0;
  var subchid = '';
  var fuid = ''; //用户来源分享的uid
  var titleid = 1; //分享设置图片id，用户区分图片来源,分享接口返回,默认传1
  var intoType = 0;//进入类型
  let formappid = ''
  if (referrerInfo.appId) {
    formappid = referrerInfo.appId
  }
  if (query.chid) {   //链接进入
    chid = query.chid;
    subchid = query.subchid ? query.subchid : '';
    fuid = query.fuid ? query.fuid : '';
    titleid = query.titleid ? query.titleid : 1;
  } else if (query.scene) { //小程序码扫描进入，通过透传的场景值中解析chid和subchid
    var sceneObj = {};
    var sceneList = decodeURIComponent(query.scene).split(",");
    for (var i = 0; i < sceneList.length; i++) {
      var sceneItem = sceneList[i];
      sceneObj[sceneItem.split(":")[0]] = sceneItem.split(":")[1];
    }
    if (sceneObj.chid) {
      chid = sceneObj.chid;
      subchid = sceneObj.subchid ? sceneObj.subchid : '';
      fuid = sceneObj.fuid ? sceneObj.fuid : '';
      titleid = sceneObj.titleid ? sceneObj.titleid : 1;
    }
  } else if (referrerInfo.extraData) {  // 新增  通过小程序 extra-data传值进入
    if (typeof (referrerInfo.extraData) === "string") {
      referrerInfo.extraData = JSON.parse(referrerInfo.extraData);
    }
    chid = referrerInfo.extraData.chid;
    subchid = referrerInfo.extraData.subchid;
    fuid = referrerInfo.extraData.fuid ? referrerInfo.extraData.fuid : '';
    titleid = referrerInfo.extraData.titleid ? referrerInfo.extraData.titleid : 1;
    if (formappid == '') {
      formappid = referrerInfo.extraData.scene ? referrerInfo.extraData.scene : ''
    }
  } else {
    intoType = 1
  }
  var res = { chid: chid, subchid: subchid, fuid: fuid, titleid: titleid, formappid: formappid, intoType:intoType }
  console.log(res)
  return res
}
initShader(gl, function (shaderProgram) {
    gl.program = shaderProgram;
    var plane = initPlane(gl);
    var fbo = initFramebufferObject(gl);
    initTextures(gl, function (texture) {
      draw(gl, plane, texture, fbo);
      start();
    });
 });
 wx.showLoading({
  tile:'加载中...',
  mask:true
});
function start() {
  wx.login({
    success: function (res2) {
      var res = onGetChid()
      var reporData = {
        code: res2.code,
        gameid: 439,
        appid: 'wx06fdf9020e8bd0d3',
        chid: res.chid,
        subchid: res.subchid,
        formappid: res.formappid,
      }
      console.log("djsLoginData>>", reporData)
      wx.request({
        url: "https://wxlogin.djsh5.com/wxlogin?cmd=wxaLogin",
        data: reporData,
        method: 'POST',
        success: function (result) {
          console.log("login>>", result)
          if (!result.data.error) {
            GameGlobal.djsLoginData = {
              chid: res.chid,
              subchid: res.subchid,
              fuid: res.fuid,
              titleid: res.titleid,
              formappid: res.formappid,
              intoType: res.intoType,
              user_id: result.data.uid,
              token: result.data.token,
            }
            // 加载引擎分包
            const loadTask = wx.loadSubpackage({ 
              name: 'mainPackage',
              success:function(){wx.hideLoading();},
              fail: function () {
                console.log("主包下载失败>>")
                start()
              },
            })
          } else {start()}
        },
        fail: function () {start()}
      })
    },
    fail: function () {start()}
  });
}